<template>
  <s-clean-layout :title="isEdit ? '更多' : '添加笔记'" navbar="normal">
    <view class="note-edit-container">
      <!-- 表单内容 -->
      <scroll-view scroll-y class="form-container">
        <!-- 编辑区域 -->
        <view class="edit-card">
          <!-- 标题输入 -->
          <view class="input-area">
            <input
              type="text"
              v-model="title"
              placeholder="请出入标题..."
              class="title-input"
            />
          </view>

          <!-- 内容输入 -->
          <view class="input-area">
            <textarea
              v-model="content"
              placeholder="请输入内容..."
              class="content-textarea"
              maxlength="500"
            />
          </view>
        </view>

        <!-- 添加图片 -->
        <view class="add-image-card">
          <view class="add-image-item" @tap="chooseImage">
            <view class="add-image-text">添加图片</view>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
          
          <!-- 添加图片展示区域 -->
          <view class="image-list" v-if="imageList.length > 0">
            <view v-for="(image, index) in imageList" :key="index" class="image-item">
              <image :src="image" mode="aspectFill" @tap="previewImage(index)"></image>
              <view class="delete-btn" @tap.stop="deleteImage(index)">
                <text class="delete-icon">×</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 底部间距，确保内容不被底部保存按钮遮挡 -->
        <view style="height: 120rpx;"></view>
      </scroll-view>
      
      <!-- 底部保存按钮 -->
      <view class="bottom-save-button" @tap="saveNote">
        <text>完成</text>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import UserArticleApi from '@/sheep/api/article/user_article';
import FileApi from '@/sheep/api/infra/file';

// 编辑模式标志
const isEdit = ref(false);

// 表单数据
const title = ref('');
const content = ref('');
const imageList = ref([]);
const fileUrl = ref('');

// 联系人ID和记录ID
const contactId = ref('');
const noteId = ref('');

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - imageList.value.length, // 最多9张图片
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      uni.showLoading({
        title: '上传中...'
      });
      
      try {
        // 上传选中的图片
        for (const tempFilePath of res.tempFilePaths) {
          const result = await FileApi.uploadFile(tempFilePath);
          if (result && result.data) {
            imageList.value.push(result.data);
            // 如果是第一张图片，设为封面
            if (imageList.value.length === 1) {
              fileUrl.value = result.data;
            }
          }
        }
      } catch (error) {
        console.error('上传图片失败:', error);
        uni.showToast({
          title: '上传图片失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  });
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    urls: imageList.value,
    current: imageList.value[index]
  });
};

// 删除图片
const deleteImage = (index) => {
  imageList.value.splice(index, 1);
  // 如果删除的是第一张图片，更新封面
  if (index === 0 && imageList.value.length > 0) {
    fileUrl.value = imageList.value[0];
  } else if (imageList.value.length === 0) {
    fileUrl.value = '';
  }
};

// 查询文章详情
const getArticleDetail = async (id) => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const res = await UserArticleApi.queryArticleDetail({ id });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      title.value = res.data.title || '';
      content.value = res.data.content || '';
      
      // 处理图片数据，将逗号分隔的字符串转为数组
      if (res.data.fileUrl) {
        imageList.value = res.data.fileUrl.split(',');
        fileUrl.value = res.data.fileUrl;
      }
    } else {
      uni.showToast({
        title: res.msg || '获取详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取文章详情失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 保存笔记
const saveNote = async () => {
  // 验证数据
  if (!title.value) {
    uni.showToast({
      title: '请输入标题',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: isEdit.value ? '更新中...' : '保存中...'
    });
    
    // 构建请求参数
    const params = {
      id: isEdit.value ? noteId.value : null,
      title: title.value,
      content: content.value,
      businType: 'CONTACT_REMARK',
      categoryType: 'CONTACT_REMARK',
      businId: contactId.value, // 添加联系人ID
      fileUrl: imageList.value.join(',') // 多张图片地址用逗号隔开
    };
    
    const res = await UserArticleApi.addOrUpdateArticle(params);
    
    uni.hideLoading();
    
    if (res.code === 0) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '保存成功',
        icon: 'success'
      });
      // 直接返回上一页，由上一页的onShow方法负责刷新数据
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    } else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存文章失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 在onMounted中获取页面参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id, contactId: cId, mode } = currentPage.options;
  
  isEdit.value = mode === 'edit';
  contactId.value = cId;
  
  if (isEdit.value && id) {
    // 编辑模式：获取现有笔记数据
    noteId.value = id;
    getArticleDetail(id);
  }
});
</script>

<style lang="scss" scoped>
.note-edit-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 移除原有的header样式 */
.header {
  display: none;
}

/* 修改表单容器样式 */
.form-container {
  height: calc(100vh - 44px - var(--status-bar-height));
  padding-top: 20rpx;
  box-sizing: border-box;
}

/* 底部保存按钮样式 */
.bottom-save-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 90rpx;
  background-color: #2196F3;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  z-index: 100;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  border-radius: 45rpx;
  margin-bottom: env(safe-area-inset-bottom);
}

.edit-card {
  background-color: #fff;
  padding: 0 30rpx;
  margin-bottom: 20rpx;
}

.input-area {
  margin-bottom: 20rpx;
}

.title-input {
  font-size: 32rpx;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.content-textarea {
  width: 100%;
  height: 240rpx;
  font-size: 28rpx;
  line-height: 1.5;
  padding: 30rpx 0;
}

.add-image-card {
  background-color: #fff;
  margin-top: 20rpx;
}

.add-image-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  margin: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.add-image-text {
  font-size: 28rpx;
  color: #333;
}

/* 添加图片列表样式 */
.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
}

.image-item image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: #fff;
  font-size: 32rpx;
  line-height: 1;
}
</style>